from apps.common.base.dao import BaseDao
from apps.merchant.item.serializers import *
from django.db.models import F
from apps.merchant.shop.dao import ShopDao
from apps.user.dao import UserDao
from apps.common.extension.customException import *

class ItemDao(BaseDao):
    MODEL_CLASS = Item
    SERI_CLASS = ItemBaseSerializer

    def create(self, data):
        try:
            # 如果没有选择商户，默认为自营商户
            if not data.get('shop'):
                # 如果是加盟店，归属到该加盟店
                admin = UserDao().findOneByObjId(data.get('requestUserId'))
                if admin.role.key == '加盟店':
                    if not admin.admin_shop.all().exists():
                        raise VerifyException('该账号下没有加盟店！')
                    data['shop'] = admin.admin_shop.all().first().id
                else:
                    data['shop'] = ShopDao().findAll().filter(types='0').first().id
            # 调用父类的 create 方法
            shop_instance = super().create(data)
            return shop_instance
        except Exception as e:
            raise e
    
    # 获取所有商品
    def findAllItem(self):
        return ItemDao().findAll().select_related('cate', 'activity', 'genera', 'shop', 'supplier', 'brand').prefetch_related('item_sku', 'tags')

    def findAllItemForC(self):
        return self.findAllItem().filter(checkStatus='PASS', status=1, shop__checkStatus='PASS', shop__is_delete=False)
    # 获取自营商品
    def findSelfItem(self):
        return self.findAllItem().filter(shop__types='0')
    
    # 获取结盟店商品
    def findFranchiseeItem(self):
        return self.findAllItem().filter(shop__types='1')
    

    # 增加销量
    def addSales(self, itemId, n):
        item = ItemDao().findOneByObjId(itemId)
        item.sales = F('sales') + n
        item.save()

    # 减少销量
    def subSales(self, itemId, n):
        item = ItemDao().findOneByObjId(itemId)
        item.sales = F('sales') - n
        item.save()